<template>
  <div class="borrow-form">
    <div class="page-header">
      <h2>{{ isEdit ? '编辑借阅' : '添加借阅' }}</h2>
      <el-button @click="goBack">返回列表</el-button>
    </div>

    <div class="form-section">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户" prop="userId">
              <el-select v-model="formData.userId" placeholder="请选择用户" style="width: 100%">
                <el-option
                  v-for="user in users"
                  :key="user.id"
                  :label="user.username"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图书" prop="bookId">
              <el-select v-model="formData.bookId" placeholder="请选择图书" style="width: 100%">
                <el-option
                  v-for="book in books"
                  :key="book.id"
                  :label="book.title"
                  :value="book.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="借阅日期" prop="borrowDate">
              <el-date-picker
                v-model="formData.borrowDate"
                type="date"
                placeholder="请选择借阅日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计归还日期" prop="expectedReturnDate">
              <el-date-picker
                v-model="formData.expectedReturnDate"
                type="date"
                placeholder="请选择预计归还日期"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            {{ isEdit ? '更新' : '添加' }}
          </el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import borrowApi from '@/api/borrow'
import userApi from '@/api/user'
import bookApi from '@/api/book'

const router = useRouter()
const route = useRoute()

const formRef = ref(null)
const isEdit = computed(() => !!route.params.id)
const submitting = ref(false)

const users = ref([])
const books = ref([])

const formData = reactive({
  id: null,
  userId: null,
  bookId: null,
  borrowDate: '',
  expectedReturnDate: '',
  remark: ''
})

const formRules = reactive({
  userId: [{ required: true, message: '请选择用户', trigger: 'change' }],
  bookId: [{ required: true, message: '请选择图书', trigger: 'change' }],
  borrowDate: [{ required: true, message: '请选择借阅日期', trigger: 'change' }],
  expectedReturnDate: [{ required: true, message: '请选择预计归还日期', trigger: 'change' }]
})

const goBack = () => router.push('/borrow')

const handleReset = () => {
  formRef.value?.resetFields()
}

const getUsers = async () => {
  try {
    const result = await userApi.getList({ pageSize: 1000 })
    if (result && result.result) {
      users.value = result.result
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

const getBooks = async () => {
  try {
    const result = await bookApi.getList({ pageSize: 1000 })
    if (result && result.result) {
      books.value = result.result
    }
  } catch (error) {
    console.error('获取图书列表失败:', error)
  }
}

const getBorrowDetail = async (id) => {
  try {
    const result = await borrowApi.getById(id)
    if (result) {
      Object.assign(formData, result)
    }
  } catch (error) {
    ElMessage.error('获取借阅详情失败: ' + error.message)
    goBack()
  }
}

const handleSubmit = async () => {
  try {
    const valid = await formRef.value?.validate()
    if (!valid) return

    submitting.value = true

    if (isEdit.value) {
      await borrowApi.update(formData)
      ElMessage.success('更新借阅成功')
    } else {
      await borrowApi.borrow(formData)
      ElMessage.success('添加借阅成功')
    }

    goBack()
  } catch (error) {
    ElMessage.error((isEdit.value ? '更新' : '添加') + '借阅失败: ' + error.message)
  } finally {
    submitting.value = false
  }
}

onMounted(async () => {
  await Promise.all([getUsers(), getBooks()])
  
  if (isEdit.value && route.params.id) {
    getBorrowDetail(route.params.id)
  }
})
</script>

<style scoped>
.borrow-form {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.form-section {
  background: #fff;
  padding: 30px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>
